//
//  Stack.c
//  algorithmDemo
//
//  Created by 李文深 on 16/8/21.
//  Copyright © 2016年 30pay. All rights reserved.
//

#include "Stack.h"
#include "FatalError.h"
#include <stdlib.h>
#include <string.h>

#define MAX_STACK_SIZE 10

pStack initStack() {
    
    pStack s = (pStack)malloc(MAX_STACK_SIZE * sizeof(struct Stack));
    
    if (s == NULL) {
        FatalError("初始化失败");
        return NULL;
    }
    
    s->top = s->base = s;
    s->size = 0;
    
    return s;
}


void push(pStack s ,ElementType e) {
    if (s->size == MAX_STACK_SIZE) {
        printf("栈元素已经满了\n");
        return;
    }
    
    s->top ++;
    s->top->data = e;
    s->size ++;
    
}

int pop(pStack s ,ElementType *e){
    if (s->size == 0) {
        return 0;
    }
    *e = s->top->data;
    s->top --;
    s->size --;
    return 1;
}

int size(pStack s) {
    return (int)(s->top - s->base);
}

int isEmpty(pStack s) {
    return s->size == 0;
}


int my_getline(char* line, int max_size)
{
    int c;
    int len = 0;
    while( (c = getchar()) != EOF && len < max_size ){
        line[len++] = c;
        if('\n' == c)
            break;
    }
    
    line[len-1] = '\0';
    return len;
}


int parse(pStack s,char *str) {
    
    size_t len = strlen(str);
    
    int isMatch = 0;
    
    for (int i = 0; i<len; i++) {
        
        switch (str[i]) {
            case '{':
            case '(':
            case '[':
                push(s, str[i]);
                break;
                
            case '}':
            case ')':
            case ']':
            {
                char e;
                if (pop(s, &e) && isEmpty(s)) {
                    
                    if ((str[i] == '}' && e == '{') ||
                        (str[i] == ')' && e == '(') ||
                        (str[i] == ']' && e == '[')) {
                        isMatch = 1;
                    }
                    
                }else {
                    isMatch = 0;
                }
            }
                break;
                
            default: //含有非括号的字符
                return 0;
        }
        
    }
    
    return isMatch;
}

